/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import com.google.android.imageloader.ImageLoader;

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.EventData;
import edu.bsu.android.gtv.apps.bconnected.objects.Event;
import edu.bsu.android.gtv.apps.bconnected.ui.base.BaseActivity;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.UIUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

/**
 * An activity that shows detail information for a event including description and contact info. Activity that is started when a user selects an 
 * event from the list on the {@link EventFragment}.
 * @author Kyle Parker, University Computing Services
 */
public class EventInfoActivity extends BaseActivity {
    private static final String TAG = "EventInfoActivity";
    private static final String TAG_CONTACT = "contact";
    private static final String TAG_DESCRIPTION = "desc";

    private TabHost mTabHost;
    private View mLoadingSpinner;
    private Activity mActivity;
    private Event mEvent;
    
    private String mEventName;
    private String mUrl;
    private String mBuildingDesc;
    private String mLatitude;
    private String mLongitude;

    private int mEventID = 0;
    private String mEventTypeID;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event_info);
		
        getActivityHelper().setupActionBar(false, "Campus Events | Event Info");
        
        mActivity = this;
                
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
       	mTabHost.setup();

        mLoadingSpinner = findViewById(R.id.loading_spinner); 
        mLoadingSpinner.setVisibility(View.VISIBLE);

        setupDescriptionTab();
        setupContactInfoTab();

        getExtras();
		
		// Hide the event information while the data is loading
		hideEventInfo();
		loadEventInfo();

        AnalyticsUtils.getInstance(mActivity).trackPageView("/EventInfo");
    }
    
    /**
     * Get the extras from the Intent
     */
    public void getExtras() {
		Bundle extras = getIntent().getExtras(); 
 
		if (extras != null) {
			if (extras.getString(Constants.EXTRA_EVENT_ID) != null) {
				mEventID = Integer.parseInt(extras.getString(Constants.EXTRA_EVENT_ID));
			}
			if (extras.getString(Constants.EXTRA_EVENT_TYPE_ID) != null) {
				mEventTypeID = extras.getString(Constants.EXTRA_EVENT_TYPE_ID);
			}
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the event information from the service handler
     */
    public void loadEventInfo() {		
        Runnable load = new Runnable(){
            public void run() {
            	try {
	    	        // Display the event information
	    	        EventData.initializeEvent(mEventID, mEventTypeID,  mActivity);
	
	                if (EventData.getEventCount() > 0) {
	                	mEvent = EventData.getEvent(0);

	            		if (mEvent.getImageURL() != null) {
		                    ImageLoader imageLoader = new ImageLoader();
		                    
		                    ImageView image = (ImageView) findViewById(R.id.building_photo);
		                    image.setTag(mEvent.getImageURL().toString());
		                    image.setContentDescription(mEvent.getBuildingDesc());
		                    imageLoader.bind(image, mEvent.getImageURL().toString(), null);
	            		}
	                }
	    	    	
	    	    	mActivity.runOnUiThread(returnEvent);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread = new Thread(null, load, "loadEventInfo");
        thread.start();
    }
    
    /**
     * Load the event info from the service handler and set the visibility of the spinner to "gone"
     */
    private Runnable returnEvent = new Runnable(){
        public void run() {
        	displayEventInfo();
            mLoadingSpinner.setVisibility(View.GONE);
        }
    };
    
    /**
     * Display the event information
     */
    private void displayEventInfo() {
    	if (mEvent != null) {
    		LinearLayout view = (LinearLayout) findViewById(R.id.event_info_container);
	        view.setVisibility(View.VISIBLE);
        	view.setBackgroundResource(R.color.content_background);
	        
	    	mEventName = mEvent.getEventName();
	    	mUrl = mEvent.getShareURL().toString();
	    	mBuildingDesc = mEvent.getBuildingDesc();
	    	mLatitude = mEvent.getLatitude();
	    	mLongitude = mEvent.getLongitude();
	    	        
	    	String eventDate = mEvent.getBeginDate(); 
	    	String eventTime = mEvent.getBeginTime(); 
	    	String venue = "";
	    	String cost = "";
	    	String audience = "";
	    	
	    	if (mEvent.getEndDate().length() > 0 && !mEvent.getEndDate().matches(mEvent.getBeginDate())) {
	    		eventDate = eventDate + " - " + mEvent.getEndDate();
	    	}    	
	    	if (mEvent.getEndTime().length() > 0 && !mEvent.getEndTime().matches(mEvent.getBeginTime())) {
	    		eventTime = eventTime + " - " + mEvent.getEndTime();
	    	}
	    	if (mEvent.getLocation().length() > 0 || mEvent.getBuildingDesc().length() > 0) {
	    		venue = "Venue: ";
	    		
				if (mEvent.getBuildingDesc().length() > 0) {
		    		venue = venue + mEvent.getBuildingDesc();
		    		
					if (mEvent.getLocation().length() > 0) {
		        		venue = venue + " - ";
					}
					
				}
				
	    		venue = venue + mEvent.getLocation();    		
	    	}
	    	if (mEvent.getCost().length() > 0) {
	    		cost = "Cost: " + mEvent.getCost();
	    	}
	    	if (mEvent.getAudience().length() > 0) {
	    		audience = "Audience: " + mEvent.getAudience(); 
	    	}    	
	    	if (audience.length() > 0 || cost.length() > 0) {
	            findViewById(R.id.header_additional_info).setVisibility(View.VISIBLE);
	    	}

	    	UIUtils.displayTextView(view, R.id.event_name, mEvent.getEventName());
	    	UIUtils.displayTextView(view, R.id.calendar, mEvent.getCalendarEventName());
	    	UIUtils.displayTextView(view, R.id.event_time, eventTime);
	    	UIUtils.displayTextView(view, R.id.event_date, eventDate);
	    	UIUtils.displayTextView(view, R.id.venue, venue);
	    	UIUtils.displayTextView(view, R.id.cost, cost);
	    	UIUtils.displayTextView(view, R.id.event_desc, mEvent.getEventDesc());
	    	UIUtils.displayTextView(view, R.id.audience, audience);
	
	    	if (mEvent.getContactName().length() > 0) {
	            findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
	            findViewById(R.id.name).setVisibility(View.VISIBLE);
	            UIUtils.displayTextView(view, R.id.name, mEvent.getContactName());
	    	}
	    	if (mEvent.getContactEmail().length() > 0) {
	            findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
	            findViewById(R.id.email).setVisibility(View.VISIBLE);
	            UIUtils.displayTextView(view, R.id.email, mEvent.getContactEmail());
	    	}
	    	if (mEvent.getContactPhone().length() > 0) {
	            findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
	            findViewById(R.id.phone).setVisibility(View.VISIBLE);
	            UIUtils.displayTextView(view, R.id.phone, mEvent.getContactPhone());
	    	}
	    	         
	    	if (mEvent.getLatitude().length() > 0 && mEvent.getLongitude().length() > 0) {
		    	// Display the standard map graphic and launch the Google Maps intent when tapped
		    	ImageView image = (ImageView) findViewById(R.id.campus_map);
		    	image.setVisibility(View.VISIBLE);
		    	
		    	image.setImageResource(R.drawable.campus_map);
		    	image.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
		            	Intent intent = UIUtils.getGoogleMapsIntent(mBuildingDesc, mLatitude, mLongitude);
		            	
		            	if (intent != null) {
		            		startActivity(intent);
		            	} else {
		                    final String errorText = mActivity.getString(R.string.toast_error_location); 
		                    Toast.makeText(mActivity, errorText, Toast.LENGTH_LONG).show();
		            	}
					}
				});
	    	}
    	} else {
    		hideEventInfo();
    		((TextView) showEmptyEventInfo().findViewById(R.id.empty_event_info)).setText(R.string.empty_event_info);
    	}
    }

    /**
     * Hide the event view during the load process or if the event object is empty
     */
    private void hideEventInfo() {  
    	LinearLayout view = (LinearLayout) findViewById(R.id.event_info_container);
        view.setVisibility(View.GONE);			
    }

    /**
     * Show the event view during the load process or if the event object is empty
     */
	private View showEmptyEventInfo() {
		LinearLayout view = (LinearLayout) findViewById(R.id.empty_event_info_container);
		view.setVisibility(View.VISIBLE);
        view.setBackgroundResource(R.drawable.empty_events); 
        
        return view;
	}

    /**
     * Build and add "description" tab.
     */
    private void setupDescriptionTab() {
        mTabHost.addTab(mTabHost.newTabSpec(TAG_DESCRIPTION)
                .setIndicator(UIUtils.buildIndicator(R.string.tab_description, mActivity))
                .setContent(R.id.tab_event_desc));
    }
    
    /**
     * Build and add "contact info" tab.
     */
    private void setupContactInfoTab() {
        mTabHost.addTab(mTabHost.newTabSpec(TAG_CONTACT)
                .setIndicator(UIUtils.buildIndicator(R.string.tab_contact_info, mActivity))
                .setContent(R.id.tab_contact_info));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = new MenuInflater(this);
    	inflater.inflate(R.menu.event_info_menu_items, menu);
    	
    	super.onCreateOptionsMenu(menu);
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final String shareString;
        final Intent intent;

        switch (item.getItemId()) {
            case R.id.menu_share:
                shareString = mActivity.getString(R.string.content_event_share) + " " + mEventName + " at " + mUrl;
                intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, mEventName);
                intent.putExtra(Intent.EXTRA_TEXT, shareString);
                startActivity(Intent.createChooser(intent, getText(R.string.title_share)));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
